package com.mk.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.mk.common.ThreadLocalUtil;
import com.mk.config.CosClientConfig;
import com.mk.contants.UserConstant;
import com.mk.exception.BusinessException;
import com.mk.exception.ErrorCode;
import com.mk.exception.ThrowUtils;
import com.mk.model.dto.file.UploadPictureResult;
import com.mk.model.entity.User;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文件服务
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    @Resource
    private COSClient cosClient;

    /**
     * 上传图片，返回图片基础信息
     * @param multipartFile 上传文件
     * @param uploadPathPrefix 基础前缀
     * @return
     */
    public UploadPictureResult uploadPictureResult(MultipartFile multipartFile, String uploadPathPrefix){
        // 校验图片
        this.validPicture(multipartFile);
        // 获取登录用户信息
        User user = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        // 3. 封装返回图片信息 （设置唯一Id, 存储路径）
        String originalName = multipartFile.getOriginalFilename();
        String uuid = RandomUtil.randomString(16);
        log.info("随机生成的uuid: {}", uuid);
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalName));
        String uploadPath = String.format("%s/%s", uploadPathPrefix, uploadFileName);

        // 生成临时文件,上传文件
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 封装上传图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();

            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(String.format("%s/%s", cosClientConfig.getHost(), uploadPath));
            uploadPictureResult.setPicName(FileUtil.mainName(originalName));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            // 临时文件清理
            this.deleteTempFile(file);
        }
    }

    /**
     * 上传图片，返回图片基础信息 （根据Url）
     * @param uploadPathPrefix 基础前缀
     * @return
     */
    public UploadPictureResult uploadPictureResult(String fileUrl, String uploadPathPrefix){
        // 校验图片
        this.validPictureUrl(fileUrl);
        // 获取登录用户信息
        User user = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        // 3. 封装返回图片信息 （设置唯一Id, 存储路径）
        String originalName = FileUtil.mainName(fileUrl);
        String uuid = RandomUtil.randomString(16);
        log.info("随机生成的uuid: {}", uuid);
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originalName));
        String uploadPath = String.format("%s/%s", uploadPathPrefix, uploadFileName);

        // 生成临时文件,上传文件
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            long downloadFile = HttpUtil.downloadFile(fileUrl, file);
            log.info("HttpUtil.downloadFile(fileUrl, file)URL下载文件返回值：{}", downloadFile);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 封装上传图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();

            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(String.format("%s/%s", cosClientConfig.getHost(), uploadPath));
            uploadPictureResult.setPicName(FileUtil.mainName(originalName));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            // 临时文件清理
            this.deleteTempFile(file);
        }
    }

    /**
     * 校验Url
     * @param fileUrl
     */
    private void validPictureUrl(String fileUrl) {
        ThrowUtils.throwIf(fileUrl == null, ErrorCode.PARAMS_ERROR, "图片地址不能为空");
        ThrowUtils.throwIf(fileUrl.length() > 1024, ErrorCode.PARAMS_ERROR, "Url过长");
        // 1. 检验URL格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }
        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3. 校验图片能否正常下载
        HttpResponse response =null;
        try{
            // 发送 HEAD 请求以验证文件是否存在
           response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();

            // url地址支持HEAD
           if (HttpStatus.HTTP_ACCEPTED == response.getStatus()){
               // 校验文件类型
               String contentType = response.header("Content-Type");
               if (StrUtil.isNotBlank(contentType)){
                   // 允许的图片类型
                   final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                   ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                           ErrorCode.PARAMS_ERROR, "文件类型错误");
               }
               // 校验文件大小
               String contentLengthStr = response.header("Content-Length");
               if (StrUtil.isNotBlank(contentLengthStr)) {
                   try {
                       long contentLength = Long.parseLong(contentLengthStr);
                       final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                       ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                   } catch (NumberFormatException e) {
                       throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                   }
               }
           }
        }catch (Exception e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "Url地址请求失败");
        }finally {
            if (response != null) {
                response.close();
            }
        }
        // URL不支持HEAD请求 发送 get 请求以验证文件是否存在, 直接尝试下载
    }


    /**
     * 检验图片
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1. 校验文件大小
        final long ONE_M = 1024 * 1024;
        Long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.FORBIDDEN_ERROR, "图片大小不能超过2MB");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀列表（或者集合）
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "png", "jpg", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }
    /**
     * 清理临时文件
     * @param file
     */
    private void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
}
